package com.haruhinav.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    private static final String SING = "!^H#a$r^Uh_i$";

    /*
    * 生成token
    * */
    public static String createToken(Map<String,String> map){
        //过期时间
        Calendar instance =  Calendar.getInstance();
        instance.add(Calendar.DATE,7);

        //创建jwt
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        String token = builder.withExpiresAt(instance.getTime())//指定过期时间
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     * 验证token
     * */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    /**
     * 从token获得uid
     * */

    public static int fromTokenGetUid(HttpServletRequest request){
        String token = request.getHeader("token");
        return Integer.parseInt(JWTUtils.verify(token).getClaim("userid").asString());
    }
    /**
     * 从token获得验证admin
     * */

    public static int fromTokenGetAdmin(HttpServletRequest request){
        String token = request.getHeader("at");
        return Integer.parseInt(JWTUtils.verify(token).getClaim("userid").asString());
    }
}
